import { minganciData } from './minganciData.js'
import { ChatUtils } from './chatUtils.js';
import { minganciBiaoshu, zhudongCancel } from './type'

/** 小程序gpt流式请求 */
export class XCXChatUtils extends ChatUtils {

	/** 用户取消标识是否开启 */
	static isCancel = false;

	/** 是否开启敏感词标识 */
	static isMinganci = false;

	/** 停止请求 */
	static stopRequest() {
		this.source.abort();
		this.isCancel = true;
	}
	/** 接口请求 */
	static request(data, onUpdateBack, url = 'chat-process') {
		return new Promise((resolve, reject) => {

			let failNum = 0;
			this.isMinganci = false;
			this.isCancel = false;

			const fn = async _ => {
				this.source = uni.request({
					url: `https://chat.hhchatai.com/${url}`,
					method: 'POST',
					data,
					success: res => {
						const info = this._getResponseData(res.data, true)
						if (info.result) {
							if (minganciData.some(str => ~info.result.indexOf(str)))
								resolve({
									fail: false,
									isEnd: true,
									result: zhudongCancel,
									id: "",
								})
							else resolve(info);
						} else if (this.isMinganci) {
							resolve({
								fail: false,
								isEnd: true,
								result: minganciBiaoshu,
								id: "",
							});
						} else {
							resolve({
								fail: false,
								isEnd: true,
								result: "",
								id: "",
							})
						}

					},
					fail: error => {
						if (this.isCancel) {
							resolve({
								fail: false,
								isEnd: true,
								result: zhudongCancel,
								id: "",
							});
						} else if (this.isMinganci) {
							resolve({
								fail: false,
								isEnd: true,
								result: minganciBiaoshu,
								id: "",
							});
						} else {
							if (failNum > 6) reject(err)
							else fn();
							failNum++;
						}
						this.isCancel = false;
						this.isMinganci = false;
					}
				})
			}

			fn();

		})
	}
}